<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta name="description" content="这是一个简单的博客" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>Spring ResponseEntity 详解 |  小刘的博客</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      
<link rel="stylesheet" href="/css/fonts/remixicon.css">

      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.staticfile.org/pace/1.2.4/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="小刘的博客" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Spring-ResponseEntity-详解"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Spring ResponseEntity 详解
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2023/12/08/Spring-ResponseEntity-%E8%AF%A6%E8%A7%A3/" class="article-date">
  <time datetime="2023-12-08T02:38:06.000Z" itemprop="datePublished">2023-12-08</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/JAVA/">JAVA</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/JAVA/%E5%AD%A6%E4%B9%A0/">学习</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.1k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">8 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>Spring ResponseEntity 是一个类，它表示整个 HTTP 响应，包括状态码，标头和正文。我们可以使用它来完全配置 HTTP 响应。如果我们想使用它，我们必须从端点返回它；Spring 会处理其余的部分。</p>
<p>ResponseEntity 继承了 HttpEntity 类，HttpEntity 代表一个 HTTP 请求或者响应实体，其内部有两个成员变量：header 和 body，代表 HTTP 请求或响应的 header 和 body，其中的 body 是泛型的。</p>
<p>ResponseEntity 扩展了 HttpEntity 类，新增了 status 成员变量，这样，一个 ResponseEntity 基本可以代表完整的 HTTP 的请求或响应了。我们可以使用它来完全配置 HTTP 响应，包括状态码，标头和正文。</p>
<p>当我们在控制器层返回 ResponseEntity 对象时，Spring MVC 框架会使用 <strong>HttpEntityMethodProcessor</strong> 类来处理它。<strong>HttpEntityMethodProcessor</strong> 是 AbstractMessageConverterMethodProcessor 的一个子类，它专门处理返回值类型是 HttpEntity 或 ResponseEntity 的控制器方法。</p>
<p>HttpEntityMethodProcessor 的处理过程如下：</p>
<ul>
<li>首先，检查返回值是否为空，如果为空，就直接返回。</li>
<li>然后，创建 ServletServerHttpRequest 和 ServletServerHttpResponse 对象，用于读取请求和写入响应。</li>
<li>接着，断言返回值是 HttpEntity 类型的，并将其强制转换为 HttpEntity 或 ResponseEntity 对象。</li>
<li>然后，获取输出消息的标头和实体标头，并将实体标头复制到输出标头中。</li>
<li>接着，判断返回值是否是 ResponseEntity 类型的，并获取其状态码，并设置到输出消息中。</li>
<li>最后，调用父类的 writeWithMessageConverters 方法，根据实体类型和请求内容协商选择合适的消息转换器，并将实体内容写入到输出消息中。</li>
</ul>
<p>handleReturnValue 是HttpEntityMethodProcessor类的一部分，用来处理返回值类型是 HttpEntity 或 ResponseEntity 的控制器方法，源码说明如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception &#123;</span><br><span class="line">        // 设置 mavContainer 的 requestHandled 属性为 true，表示请求已经被处理，不需要再渲染视图。</span><br><span class="line">        mavContainer.setRequestHandled(true);</span><br><span class="line">        if (returnValue != null) &#123;</span><br><span class="line">            // 创建 ServletServerHttpRequest 和 ServletServerHttpResponse 对象，用于读取请求和写入响应</span><br><span class="line">            ServletServerHttpRequest inputMessage = this.createInputMessage(webRequest);</span><br><span class="line">            ServletServerHttpResponse outputMessage = this.createOutputMessage(webRequest);</span><br><span class="line">            // 断言返回值是 HttpEntity 类型的，并将其强制转换为 HttpEntity对象</span><br><span class="line">            Assert.isInstanceOf(HttpEntity.class, returnValue);</span><br><span class="line">            HttpEntity&lt;?&gt; responseEntity = (HttpEntity)returnValue;</span><br><span class="line">            HttpHeaders outputHeaders = outputMessage.getHeaders();</span><br><span class="line">            HttpHeaders entityHeaders = responseEntity.getHeaders();</span><br><span class="line">            if (!entityHeaders.isEmpty()) &#123;</span><br><span class="line">                // 获取输出消息的标头和实体标头，并将实体标头复制到输出标头中。</span><br><span class="line">                // 如果有 Vary 标头，它会特殊处理，避免重复或冲突</span><br><span class="line">                entityHeaders.forEach((key, value) -&gt; &#123;</span><br><span class="line">                    if (&quot;Vary&quot;.equals(key) &amp;&amp; outputHeaders.containsKey(&quot;Vary&quot;)) &#123;</span><br><span class="line">                        List&lt;String&gt; values = this.getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);</span><br><span class="line">                        if (!values.isEmpty()) &#123;</span><br><span class="line">                            outputHeaders.setVary(values);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125; else &#123;</span><br><span class="line">                        outputHeaders.put(key, value);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // 判断返回值是否是 ResponseEntity 类型的，并获取其状态码，并设置到输出消息中</span><br><span class="line">            if (responseEntity instanceof ResponseEntity) &#123;</span><br><span class="line">                int returnStatus = ((ResponseEntity)responseEntity).getStatusCodeValue();</span><br><span class="line">                outputMessage.getServletResponse().setStatus(returnStatus);</span><br><span class="line">                // 根据状态码和请求方法进行一些判断。</span><br><span class="line">                // 如果状态码是 200，并且请求方法是 GET 或 HEAD，并且资源没有被修改（根据 ETag 或 Last-Modified 标头），那么它会直接返回空响应。</span><br><span class="line">                if (returnStatus == 200) &#123;</span><br><span class="line">                    HttpMethod method = inputMessage.getMethod();</span><br><span class="line">                    if ((HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method)) &amp;&amp; this.isResourceNotModified(inputMessage, outputMessage)) &#123;</span><br><span class="line">                        outputMessage.flush();</span><br><span class="line">                        return;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; else if (returnStatus / 100 == 3) &#123;</span><br><span class="line">                    // 如果状态码是 3xx，并且有 location 标头，那么它会重定向到 location 的地址。</span><br><span class="line">                    String location = outputHeaders.getFirst(&quot;location&quot;);</span><br><span class="line">                    if (location != null) &#123;</span><br><span class="line">                        this.saveFlashAttributes(mavContainer, webRequest, location);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            this.writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);</span><br><span class="line">            outputMessage.flush();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p><strong>那么我们要如何使用ResponseEntity</strong>？</p>
<p>Spring ResponseEntity 是一个泛型类型。因此，我们可以使用任何类型作为响应正文：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping (&quot;/hello&quot;)</span><br><span class="line">ResponseEntity&lt;String&gt; hello() &#123;</span><br><span class="line">  return new ResponseEntity &lt;&gt; (&quot;Hello World!&quot;, HttpStatus.OK);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于我们以编程方式指定响应状态，因此我们可以根据不同的情况返回不同的状态码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping (&quot;/age&quot;)</span><br><span class="line">ResponseEntity&lt;String&gt; age(</span><br><span class="line">  @RequestParam (&quot;yearOfBirth&quot;) int yearOfBirth) &#123;</span><br><span class="line">  if (isInFuture (yearOfBirth)) &#123;</span><br><span class="line">    return new ResponseEntity &lt;&gt; (&quot;年份不正确&quot;, HttpStatus.BAD_REQUEST);</span><br><span class="line">  &#125;</span><br><span class="line">  return new ResponseEntity &lt;&gt; (&quot;你的年龄是&quot; + calculateAge (yearOfBirth), HttpStatus.OK);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此外，我们还可以设置 HTTP 标头：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping (&quot;/customHeader&quot;)</span><br><span class="line">ResponseEntity&lt;String&gt; customHeader() &#123;</span><br><span class="line">  HttpHeaders headers = new HttpHeaders ();</span><br><span class="line">  headers.add (&quot;Custom-Header&quot;, &quot;foo&quot;);</span><br><span class="line">  return new ResponseEntity &lt;&gt; (&quot;自定义头部&quot;, headers, HttpStatus.OK);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此外，ResponseEntity 还提供了两个嵌套的构建器接口：HeadersBuilder 和它的子接口 BodyBuilder。因此，我们可以通过 ResponseEntity 的静态方法访问它们的功能。</p>
<p>最简单的情况是具有正文和 HTTP 200 响应码的响应：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping (&quot;/hello&quot;)</span><br><span class="line">ResponseEntity&lt;String&gt; hello() &#123;</span><br><span class="line">  return ResponseEntity.ok (&quot;Hello World!&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于最常见的 HTTP 状态码，我们得到静态方法：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">BodyBuilder accepted();</span><br><span class="line">BodyBuilder badRequest();</span><br><span class="line">BodyBuilder created(java.net.URI location);</span><br><span class="line">HeadersBuilder&lt;?&gt; noContent();</span><br><span class="line">HeadersBuilder&lt;?&gt; notFound();</span><br><span class="line">BodyBuilder ok();</span><br></pre></td></tr></table></figure>

<p>另外，我们可以使用 BodyBuilder status(HttpStatus status) 和 BodyBuilder status(int status) 方法来设置任何 HTTP 状态。最后，使用 ResponseEntity BodyBuilder.body(T body) 我们可以设置 HTTP 响应正文：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping (&quot;/age&quot;)</span><br><span class="line">ResponseEntity&lt;String&gt; age(@RequestParam (&quot;yearOfBirth&quot;) int yearOfBirth) &#123;</span><br><span class="line">  if (isInFuture (yearOfBirth)) &#123;</span><br><span class="line">    return ResponseEntity.badRequest()</span><br><span class="line">      .body(&quot;年份不正确&quot;);</span><br><span class="line">  &#125;</span><br><span class="line">  return ResponseEntity.status(HttpStatus.OK)</span><br><span class="line">    .body(&quot;你的年龄是 &quot; + calculateAge (yearOfBirth));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ResponseEntity替代方案"><a href="#ResponseEntity替代方案" class="headerlink" title="ResponseEntity替代方案"></a><strong>ResponseEntity替代方案</strong></h3><p>虽然ResponseEntity很强大，但我们不应该滥用它。在简单的情况下，有其他的选项可以满足我们的需求，而且它们会产生更清晰的代码。</p>
<h3 id="ResponseBody"><a href="#ResponseBody" class="headerlink" title="@ResponseBody"></a><strong>@ResponseBody</strong></h3><p>在传统的Spring MVC应用中，端点通常返回渲染的HTML页面。如果我们想要返回JSON或XML格式的数据，我们可以使用@ResponseBody注解：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping(&quot;/hello&quot;)</span><br><span class="line">@ResponseBody</span><br><span class="line">public String hello() &#123;</span><br><span class="line">    return &quot;Hello World!&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样，Spring会自动将返回值转换为JSON或XML，并将其写入响应正文。</p>
<p>我们也可以使用@ResponseStatus注解来设置响应状态码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@GetMapping(&quot;/age&quot;)</span><br><span class="line">@ResponseBody</span><br><span class="line">@ResponseStatus(HttpStatus.OK)</span><br><span class="line">public String age(@RequestParam(&quot;yearOfBirth&quot;) int yearOfBirth) &#123;</span><br><span class="line">    if (isInFuture(yearOfBirth)) &#123;</span><br><span class="line">        throw new IllegalArgumentException(&quot;年份不正确&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    return &quot;你的年龄是&quot; + calculateAge(yearOfBirth);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果我们想要处理异常并返回不同的状态码，我们可以使用@ControllerAdvice和@ExceptionHandler注解：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@ControllerAdvice</span><br><span class="line">public class GlobalExceptionHandler &#123;</span><br><span class="line"></span><br><span class="line">    @ExceptionHandler(IllegalArgumentException.class)</span><br><span class="line">    @ResponseStatus(HttpStatus.BAD_REQUEST)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public String handleIllegalArgumentException(IllegalArgumentException ex) &#123;</span><br><span class="line">        return ex.getMessage();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="RestController"><a href="#RestController" class="headerlink" title="@RestController"></a><strong>@RestController</strong></h3><p>如果我们的控制器类只返回数据而不是视图，我们可以使用@RestController注解来替代@Controller注解。这样，我们就不需要在每个方法上添加@ResponseBody注解了：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">public class HelloController &#123;</span><br><span class="line"></span><br><span class="line">    @GetMapping(&quot;/hello&quot;)</span><br><span class="line">    public String hello() &#123;</span><br><span class="line">        return &quot;Hello World!&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @GetMapping(&quot;/age&quot;)</span><br><span class="line">    @ResponseStatus(HttpStatus.OK)</span><br><span class="line">    public String age(@RequestParam(&quot;yearOfBirth&quot;) int yearOfBirth) &#123;</span><br><span class="line">        if (isInFuture(yearOfBirth)) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;年份不正确&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        return &quot;你的年龄是 &quot; + calculateAge(yearOfBirth);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="ResponseEntity-和-ResponseBody-的区别"><a href="#ResponseEntity-和-ResponseBody-的区别" class="headerlink" title="ResponseEntity 和 @ResponseBody 的区别"></a><strong>ResponseEntity 和 @ResponseBody 的区别</strong></h2><p>ResponseEntity 和 @ResponseBody 都是用于处理 HTTP 响应的，但是有一些不同点：</p>
<ul>
<li><strong>ResponseEntity</strong> 是一个类，它表示整个 HTTP 响应，包括状态码，标头和正文。我们可以使用它来完全配置 HTTP 响应。如果我们想使用它，我们必须从端点返回它；Spring 会处理其余的部分。</li>
<li><strong>@ResponseBody</strong> 是一个注解，它告诉 Spring 将返回值转换为 JSON 并写入到响应体中。我们可以在方法或类上使用它，Spring 会自动选择合适的转换器。</li>
<li><strong>ResponseEntity</strong> 的优点是可以灵活地控制响应的各个方面，比如设置不同的状态码，标头和正文。它也可以用于一些特殊的场景，比如下载文件，需要设置 content-type 和特殊的状态（比如 206）。</li>
<li><strong>@ResponseBody</strong> 的优点是可以简化代码，让方法直接返回 JSON 结果，不需要构造 ResponseEntity 对象。它也可以和 @ResponseStatus 注解配合使用，来设置响应状态码。</li>
<li><strong>ResponseEntity 的优先级高于 @ResponseBody</strong>。如果返回值是 ResponseEntity 类型，那么 Spring 会直接使用它，不会检查有没有 @ResponseBody 注解。如果返回值不是 ResponseEntity 类型，那么 Spring 会检查有没有 @ResponseBody 注解，如果有就转换为 JSON。</li>
</ul>
<p>因此，我们可以根据不同的需求和场景选择使用 ResponseEntity 或者 @ResponseBody。</p>
<p>对于大多数情况，我们可以使用 @ResponseBody 注解来直接返回 JSON 结果，或者使用 @ResponseStatus 注解来设置响应状态码。对于一些需要更多定制的情况，我们可以使用 ResponseEntity 来完全控制 HTTP 响应。</p>
<h3 id="结语"><a href="#结语" class="headerlink" title="结语"></a><strong>结语</strong></h3><p>这篇文章我们主要介绍了Spring ResponseEntity的原理、使用及其替代方案，并对比了ResponseEntity 和 @ResponseBody。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          Donate
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2023/12/08/Spring-ResponseEntity-%E8%AF%A6%E8%A7%A3/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JAVA/" rel="tag">JAVA</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Spring/" rel="tag">Spring</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2023/12/08/Spring-Web%E5%B7%A5%E5%85%B7%E7%B1%BB/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Spring Web工具类
          
        </div>
      </a>
    
    
      <a href="/2023/12/07/hello-world/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Hello World</div>
      </a>
    
  </nav>

  
   
  
   
    <script src="https://cdn.staticfile.org/twikoo/1.4.18/twikoo.all.min.js"></script>
    <div id="twikoo" class="twikoo"></div>
    <script>
        twikoo.init({
            envId: ""
        })
    </script>
 
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2024
        <i class="ri-heart-fill heart_icon"></i> John Doe
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="小刘的博客"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.staticfile.org/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.staticfile.org/photoswipe/4.1.3/default-skin/default-skin.min.css">
<script src="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.staticfile.org/clipboard.js/2.0.10/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>